using System.Runtime.CompilerServices;
using BJoin.Application.WebApi.AutoDI.PublicButHidden;

[assembly: InternalsVisibleTo("Test")]

namespace BJoin.Application.WebApi.AutoDI
{
    using System;
    using System.Linq;
    using System.Reflection;
    using Microsoft.Extensions.DependencyInjection;


    /// <summary>
    /// Extensions for <see cref="Type"/>
    /// </summary>
    internal static class TypeExtensions
    {
        /// <summary>
        /// Check if type marked by <see cref="DoNotAutoRegisterAttribute"/>
        /// </summary>
        /// <param name="type">type</param>
        public static bool IsIgnoredType(this Type type)
        {
            var doNotAutoRegisterAttribute = type.GetCustomAttribute<DoNotAutoRegisterAttribute>();
            return doNotAutoRegisterAttribute != null;
        }

        /// <summary>
        /// Check if class marked by multiple lifetime attributes
        /// </summary>
        /// <param name="type">type</param>
        /// <returns></returns>
        public static bool IsMultipleLifetime(this Type type)
        {
            return type.GetCustomAttributes(typeof(RegisterWithLifetimeAttribute), true).Count() > 1;
        }

        /// <summary>
        /// Returns service lifetime
        /// </summary>
        /// <param name="type">type</param>
        /// <param name="lifetime">If no attribute then it returns the lifetime provided in the AsPublicImplementedInterfaces parameter</param>
        /// <returns></returns>
        public static ServiceLifetime GetLifetimeForClass(this Type type, ServiceLifetime lifetime)
        {
            return type.GetCustomAttribute<RegisterWithLifetimeAttribute>(true)?.RequiredLifetime ?? lifetime;
        }
    }
}